package com.zp.security.jwt.controller;

import com.zp.common.base.constant.Atom;
import com.zp.common.base.entity.LoginToken;
import com.zp.common.base.resp.BaseResp;
import com.zp.common.base.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping
public class HomeController {

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 刷新令牌
     * @return
     */
    @PostMapping("/refreshToken")
    public BaseResp refreshToken(HttpServletRequest request) {
        //从请求头中获取refreshToken
        String oldRefreshToken = request.getHeader(Atom.REFRESH_TOKEN_HEADER);
        //校验refreshToken，如果令牌已经过期
        if (jwtUtils.isTokenExpired(oldRefreshToken)) {
            return new BaseResp<>("200", "刷新令牌已经过期请重新登录");
        }

        //解析refreshToken
        String username = jwtUtils.getUsernameFromToken(oldRefreshToken);
        //生成新的accessToken
        String newAccessToken = jwtUtils.createToken(username);
        String newRefreshToken = jwtUtils.refreshToken(newAccessToken);
        LoginToken token = LoginToken.builder().accessToken(newAccessToken).refreshToken(newRefreshToken).build();
        return new BaseResp("200", "请求成功", token);
    }
}
